﻿using DongFangGuoKai.WMSPlatform.Commn.ExtendModule;
using DongFangGuoKai.WMSPlatform.Core.Repository;
using DongFangGuoKai.WMSPlatform.Domain.HZJLYModel;
using DongFangGuoKai.WMSPlatform.Domain.Models;
using DongFangGuoKai.WMSPlatform.Service.LogApp;
using DongFangGuoKai.WMSPlatform.Service.InboundOrderDetail;
using DongFangGuoKai.WMSPlatform.Service.InboundOrderDetail.DTO;
using DongFangGuoKai.WMSPlatform.WebApi.Utility.Filters;
using Microsoft.AspNetCore.Mvc;
using System.Drawing.Printing;

namespace DongFangGuoKai.WMSPlatform.WebApi.Controllers.OrderInBusiness
{
    /// <summary>
    /// 入库
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TReceivingOrderDetailController : ApiBaseController
    {
        private readonly ITReceivingOrderDetailService tReceivingOrderDetailService;
        private readonly IRepository<TReceivingBillDetail> receivingBillDetailrepost;
        private readonly IRepository<TReceivingBill> receivingBillrepost;
        private readonly IRepository<TInstruct> instructrepost;
        private readonly IRepository<UserColor> usercolorrepost;
        private readonly ILogger<TReceivingOrderDetailController> receivinglog;
        private readonly ILogService interfaceLogService;

        public TReceivingOrderDetailController(ITReceivingOrderDetailService tReceivingOrderDetailService,
            IRepository<TReceivingBillDetail> receivingBillDetailrepost,
            IRepository<TReceivingBill> receivingBillrepost,
            IRepository<TInstruct> instructrepost,
            IRepository<UserColor> usercolorrepost,
            ILogger<TReceivingOrderDetailController> receivinglog,
            ILogService interfaceLogService
            ):base(interfaceLogService)
        {
            this.tReceivingOrderDetailService = tReceivingOrderDetailService;
            this.receivingBillDetailrepost = receivingBillDetailrepost;
            this.receivingBillrepost = receivingBillrepost;
            this.instructrepost = instructrepost;
            this.usercolorrepost = usercolorrepost;
            this.receivinglog = receivinglog;
            this.interfaceLogService = interfaceLogService;
        }

        /// <summary>
        /// 查询委托单
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetReceivingBillList(int pageIndex, int pageSize)
        {
            var list = receivingBillrepost.GetList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            if (list != null)
            {
                foreach (var item in list)
                {
                    var rbd = receivingBillDetailrepost.GetList(r=>r.BillNo == item.BillNo).ToList();
                    item.BillDetailList = rbd;
                }
                return Success(list);
            }
            return Failed("查询失败！");
        }


        /// <summary>
        /// 根据物料去找委托单号
        /// </summary>
        /// <param name="materialCode"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetOrderNo(string materialCode)
        {
            var data = receivingBillDetailrepost.Get(r => r.MaterialCode == materialCode);
            if (data is null)
            {
                return Failed("未查询到委托单号");
            }
            var receivingobj = receivingBillDetailrepost.GetList(r=>r.BillNo == data.BillNo).Select(r=>new
            {
                r.MaterialCode,
                r.MaterialName
            });
            return Success(receivingobj,"查询成功");
        }

        /// <summary>
        /// 新的组垛(人工分拣/大件上架)
        /// </summary>
        /// <param name="stackingStorageDTO"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult NewStackingStorage(StackingStorageDTO stackingStorageDTO)
        {
            TInterfaceLog log = null;
            string errMsg = "";
            CreateInterfaceLog("人工分拣/大件上架", "/api/TReceivingOrderDetail/NewStackingStorage", 2, stackingStorageDTO.ToJson(), out log);
            var IsOk = tReceivingOrderDetailService.NewStackingStorage(out errMsg,stackingStorageDTO);
            if (IsOk)
            {
                receivinglog.LogInformation("人工分拣/大件上架成功" + errMsg + "入参：" + stackingStorageDTO.ToJson());
                return Success(errMsg);
            }
            receivinglog.LogError("人工分拣/大件上架失败：" + errMsg + "入参：" + stackingStorageDTO.ToJson());
            return Failed("保存失败：" + errMsg);
        }

        /// <summary>
        /// 分播墙上架样品解绑
        /// </summary>
        /// <param name="sampleCode"></param>
        /// <param name="pallCode"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult InUnbindingBoxSample(string pallCode, string sampleCode)
        {
            TInterfaceLog log = null;
            string OutMsg = "";
            CreateInterfaceLog("分播墙上架样品解绑", "/api/TReceivingOrderDetail/InUnbindingBoxSample", 2, pallCode + "," + sampleCode, out log);
            var IsOk = tReceivingOrderDetailService.InUnbindingBoxSample(pallCode, sampleCode,out OutMsg);
            if (IsOk)
            {
                receivinglog.LogInformation("人工分拣/大件上架成功" + OutMsg + "入参：" + pallCode + "," + sampleCode);
                return Success(OutMsg);
            }
            receivinglog.LogError("人工分拣/大件上架失败：" + OutMsg + "入参：" + pallCode + "," + sampleCode);
            return Failed("保存失败：" + OutMsg);
        }

        /// <summary>
        /// 查询样品所在分播墙位置
        /// </summary>
        /// <param name="sampleCode"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult SelectElectronicTagsSample(string sampleCode)
        {
            TInterfaceLog log = null;
            string OutMsg = "";
            CreateInterfaceLog("查询样品所在分播墙位置", "/api/TReceivingOrderDetail/SelectElectronicTagsSample", 2, sampleCode, out log);
            var IsOk = tReceivingOrderDetailService.SelectElectronicTagsSample(sampleCode, out OutMsg);
            if (IsOk)
            {
                receivinglog.LogInformation("人工分拣/大件上架成功" + OutMsg + "入参：" + sampleCode);
                return Success(OutMsg);
            }
            receivinglog.LogError("人工分拣/大件上架失败：" + OutMsg + "入参：" + sampleCode);
            return Failed("查询失败：" + OutMsg);
        }


        /// <summary>
        /// 满箱
        /// </summary>
        /// <param name="fullBoxRequest">托盘码（料箱）</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult FullBox(FullBoxRequest fullBoxRequest)
        {
            string errMsg;
            TInterfaceLog log;
            CreateInterfaceLog("分播墙分拣满箱", "/api/TReceivingOrderDetail/FullBox", 2, fullBoxRequest.ToJson(), out log);
            var IsOk = tReceivingOrderDetailService.FullBox(fullBoxRequest.palletCode, out errMsg);
            if (IsOk)
            {
                receivinglog.LogInformation("分播墙分拣满箱成功" + errMsg + "入参："+fullBoxRequest.ToJson());
                return Success(errMsg);
            }
            receivinglog.LogError("分播墙分拣满箱失败：" + errMsg + "入参：" + fullBoxRequest.ToJson());
            return Failed("保存失败：" + errMsg);
        }

        /// <summary>
        /// 大件上架
        /// </summary>
        /// <param name="largeStackingStorageDTO">托盘码（料箱）</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult LargeStackingStorage(LargeStackingStorageDTO largeStackingStorageDTO)
        {
            string errMsg;
            TInterfaceLog log;
            CreateInterfaceLog("大件上架", "/api/TReceivingOrderDetail/LargeStackingStorage", 2, largeStackingStorageDTO.ToJson(), out log);
            var IsOk = tReceivingOrderDetailService.LargeStackingStorage(out errMsg, largeStackingStorageDTO);
            if (IsOk)
            {
                receivinglog.LogInformation("大件上架成功" + errMsg + "入参：" + largeStackingStorageDTO.ToJson());
                return Success(errMsg);
            }
            receivinglog.LogError("大件上架失败：" + errMsg + "入参：" + largeStackingStorageDTO.ToJson());
            return Failed("保存失败：" + errMsg);
        }


        /// <summary>
        /// 完成入库新
        /// </summary>
        /// <param name="reqCode"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult NewExecInstructFinishedMaterials(string reqCode)
        {
            Guid guid; 
            TInterfaceLog log;
            CreateInterfaceLog("分播墙上架完成入库", "/api/TReceivingOrderDetail/NewExecInstructFinishedMaterials", 1, reqCode, out log);
            if (!Guid.TryParse(reqCode, out guid))
            {
                return Failed("Guid不对");
            }
            var instruct = instructrepost.Get(i => i.BusinessGroupId == guid);
            if (instruct == null)
            {
                receivinglog.LogError("未查询到对应指令" + "入参：" + reqCode);
                return Failed("未查询到对应指令");
            }
            string errMsg = "";
           
            var IsOk = tReceivingOrderDetailService.NewExecInstructFinishedMaterials(instruct, out errMsg);
            if (IsOk)
            {
                receivinglog.LogInformation("分播墙上架完成入库成功，入参：" + reqCode);
                return Success(errMsg);
            }
            receivinglog.LogError("分播墙上架完成入库失败：" + errMsg + "入参：" + reqCode);
            return Failed(errMsg);
        }

        /// <summary>
        /// 添加入库委托单
        /// </summary>
        /// <param name="addReceivingBilDTO"></param>
        /// <returns></returns>
        [HttpPost]
        [TypeFilter(typeof(CtmLogActionAsyncFilterAttribute))]
        public async Task<IActionResult> AddInboundOrders(AddReceivingBilDTO addReceivingBilDTO)
        {
            TInterfaceLog log;
            CreateInterfaceLog("Lims下传委托单", "/api/TReceivingOrderDetail/AddInboundOrders", 2, addReceivingBilDTO.ToJson(), out log);
            var IsOk = tReceivingOrderDetailService.AddOrders(addReceivingBilDTO, out string Message);
           
            if (IsOk)
            {
                receivinglog.LogInformation("Lims下传委托单成功 入参：" + addReceivingBilDTO.ToJson());
                return await SuccessAsync( "保存成功！");
            }
            receivinglog.LogError("Lims下传委托单失败：" + Message + "入参：" + addReceivingBilDTO.ToJson());
            return await FailedAsync("保存失败：" + Message);
        }

        /// <summary>
        /// 作废委托单
        /// </summary>
        /// <param name="OrderNo"></param>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(CtmLogActionAsyncFilterAttribute))]
        public IActionResult VoidOrder(string OrderNo)
        {
            string errorMsg = string.Empty;
            TInterfaceLog log;
            CreateInterfaceLog("Lims作废委托单", "/api/TReceivingOrderDetail/VoidOrder", 1, OrderNo, out log);

            var IsOk = tReceivingOrderDetailService.VoidOrder(OrderNo,out errorMsg);
            if (IsOk)
            {
                receivinglog.LogInformation("Lims作废委托单成功，入参：" + OrderNo);
                return Success(errorMsg);
            }
            receivinglog.LogError("委托单作废失败：" + errorMsg);
            return Failed("委托单作废失败：" + errorMsg);
        }

        #region 分实验室
        /// <summary>
        /// 分拣实验室
        /// </summary>
        /// <param name="sampleCode"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult SortingLaboratory(string sampleCode,int userId)
        {
            TInterfaceLog log;
            CreateInterfaceLog("电子标签分拣实验室", "/api/TReceivingOrderDetail/SortingLaboratory", 1, sampleCode + "," + userId, out log);
            if (string.IsNullOrEmpty(sampleCode)  || userId <= 0)
            {
                return Failed("参数有误");
            }
            string errorMsg = string.Empty;
            var usercolor = usercolorrepost.Get(u => u.UserId == userId);
            if (usercolor is null)
            {
                return Failed("未查询出用户所拥有的颜色");
            }
            int showColor = usercolor.ShowColor;//到时候会根据用户等候后选择的颜色来去亮
            var IsOk = tReceivingOrderDetailService.SortingLaboratory(sampleCode, showColor,out errorMsg);
            if (IsOk)
            {
                receivinglog.LogInformation("电子标签分拣实验室成功 入参：" + sampleCode + "," + userId);
                return Success(errorMsg);
            }
            receivinglog.LogError("电子标签分拣实验室失败：" + errorMsg + "入参：" + sampleCode + "," + userId);
            return Failed("点亮失败：" + errorMsg);
        }

        /// <summary>
        /// 样品分实验室满箱
        /// </summary>
        /// <param name="palletCode"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult SortingLaboratoryFull(string palletCode)
        {
            TInterfaceLog log;
            CreateInterfaceLog("电子标签分拣实验室满箱", "/api/TReceivingOrderDetail/SortingLaboratoryFull", 1, palletCode, out log);
            if (palletCode is null)
            {
                return Failed("参数有误");
            }
            var IsOk = tReceivingOrderDetailService.SortingLaboratoryFull(palletCode,out string errorMsg);
            if (IsOk)
            {
                receivinglog.LogInformation("电子标签分拣实验室满箱成功 入参：" + palletCode);
                return Success(errorMsg);
            }
            receivinglog.LogError("电子标签分拣实验室满箱失败：" + errorMsg + "入参：" + palletCode);
            return Failed("满箱失败："+ errorMsg);
        }

        //---------------------------------------------------------------------------

        /// <summary>
        /// 电子标签无箱操作样品分实验
        /// </summary>
        /// <param name="sampleCode"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult NotBoxLaboratory(string sampleCode, int userId)
        {
            TInterfaceLog log;
            CreateInterfaceLog("电子标签无箱操作样品分实验", "/api/TReceivingOrderDetail/NotBoxLaboratory", 1, sampleCode + "," + userId, out log);
            if (string.IsNullOrEmpty(sampleCode) || userId <= 0)
            {
                return Failed("参数有误");
            }
            string errorMsg = string.Empty;
            var usercolor = usercolorrepost.Get(u => u.UserId == userId);
            if (usercolor is null)
            {
                return Failed("未查询出用户所拥有的颜色");
            }
            int showColor = usercolor.ShowColor;//到时候会根据用户等候后选择的颜色来去亮
            var IsOk = tReceivingOrderDetailService.NotBoxLaboratory(sampleCode, showColor, out errorMsg);
            if (IsOk)
            {
                receivinglog.LogInformation("电子标签无箱操作样品分实验成功 入参：" + sampleCode + "," + userId);
                return Success(errorMsg);
            }
            receivinglog.LogError("电子标签无箱操作样品分实验失败：" + errorMsg + "入参：" + sampleCode + "," + userId);
            return Failed("点亮失败：" + errorMsg);
        }

        /// <summary>
        /// 分实验室的样品放箱子里
        /// </summary>
        /// <param name="sampleCode"></param>
        /// <param name="pallCode"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult SamplePutBox(string pallCode, string sampleCode)
        {
            TInterfaceLog log;
            CreateInterfaceLog("分实验室的样品放箱子里", "/api/TReceivingOrderDetail/SamplePutBox", 1, sampleCode + "," + pallCode, out log);
            if (string.IsNullOrEmpty(sampleCode) || string.IsNullOrEmpty(pallCode))
            {
                return Failed("参数有误");
            }
            string errorMsg = string.Empty;

            var IsOk = tReceivingOrderDetailService.SamplePutBox(pallCode, sampleCode, out errorMsg);
            if (IsOk)
            {
                receivinglog.LogInformation("分实验室的样品放箱子里成功 入参：" + sampleCode + "," + pallCode);
                return Success(errorMsg);
            }
            receivinglog.LogError("分实验室的样品放箱子里失败：" + errorMsg + "入参：" + sampleCode + "," + pallCode);
            return Failed("保存失败：" + errorMsg);
        }


        /// <summary>
        /// 分实验室的样品和箱子解绑
        /// </summary>
        /// <param name="sampleCode"></param>
        /// <param name="pallCode"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult SampleUnbindingBox(string pallCode, string sampleCode)
        {
            TInterfaceLog log;
            CreateInterfaceLog("分实验室的样品和箱子解绑", "/api/TReceivingOrderDetail/SampleUnbindingBox", 1, sampleCode + "," + pallCode, out log);
            if (string.IsNullOrEmpty(sampleCode) || string.IsNullOrEmpty(pallCode))
            {
                return Failed("参数有误");
            }
            string errorMsg = string.Empty;

            var IsOk = tReceivingOrderDetailService.SampleUnbindingBox(pallCode, sampleCode, out errorMsg);
            if (IsOk)
            {
                receivinglog.LogInformation("分实验室的样品和箱子解绑成功 入参：" + sampleCode + "," + pallCode);
                return Success(errorMsg);
            }
            receivinglog.LogError("分实验室的样品和箱子解绑失败：" + errorMsg + "入参：" + sampleCode + "," + pallCode);
            return Failed("解绑失败：" + errorMsg);
        }

        /// <summary>
        /// 电子标签无箱操作样品分实验室满箱
        /// </summary>
        /// <param name="palletCode"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult NotBoxLaboratoryFull(string palletCode)
        {
            TInterfaceLog log;
            if (palletCode is null)
            {
                return Failed("参数有误");
            }
            var IsOk = tReceivingOrderDetailService.NotBoxLaboratoryFull(palletCode, out string errorMsg);

            CreateInterfaceLog("样品分实验室满箱", "/api/TReceivingOrderDetail/NotBoxLaboratoryFull", 1, palletCode, out log);
            if (IsOk)
            {
                receivinglog.LogInformation("样品分实验室满箱成功 入参：" + palletCode);
                return Success(errorMsg);
            }
            receivinglog.LogError("样品分实验室满箱失败：" + errorMsg + "入参：" + palletCode);
            return Failed("满箱失败：" + errorMsg);
        }
        #endregion


        [HttpGet]
        public IActionResult Basda(int pageIndex, int pageSize)
        {
            var list = receivingBillrepost.GetList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            foreach (var item in list)
            {
                var datas = receivingBillDetailrepost.GetList(r=>r.BillNo == item.BillNo);
                foreach (var data in datas)
                {
                    data.BillId = item.Id;
                    receivingBillDetailrepost.Update(data);
                }
                
            }
            return Ok();
        }
    }
}
